/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package xq.gwt.ui.widgets.property;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import xq.gwt.mvc.model.ConversionException;
import xq.gwt.mvc.model.PropertyChangedEvent;
import xq.gwt.mvc.model.PropertyChangedListener;
import xq.gwt.mvc.model.PropertyModel;
import xq.gwt.ui.test.FeedbackForm;

/**
 *
 * @author admin
 */
public class StringPropertyPresenter implements PropertyChangedListener{
    private final TextItem textView;
    private PropertyModel model = null;
    private boolean blockPropertyChanged;

    public StringPropertyPresenter(TextItem txt){
        textView = txt;
        textView.addChangedHandler(new ChangedHandler() {

            public void onChanged(ChangedEvent event) {
                if(!blockPropertyChanged){                    
                    updateModel();
                }
            }
        });
    }

    public void setProperty(PropertyModel model){
        this.model = model;        
        updateView();
        this.model.addPropertyChangedListener(this);
    }


    private void updateView(){
        blockPropertyChanged = true;
        textView.setValue(model.getText());
        blockPropertyChanged = false;
    }

    private void updateModel(){
        blockPropertyChanged = true;
        try {
        	textView.getForm().clearFieldErrors(textView.getName(),true);
            model.setText(String.valueOf(textView.getValue()));            
        } catch (ConversionException ex) {           
            try {                
                textView.getForm().setFieldErrors(textView.getName(),ex.toString(), true);
            } catch (Exception e) {
                popupFeedback(e.getMessage());
            }

        }
        blockPropertyChanged = false;
    }

    public void propertyChanged(PropertyChangedEvent event) {
        if(!blockPropertyChanged)
            updateView();
    }

    public static void popupFeedback(String feedback){
        final Window win = new Window();
        win.setHeight(200);
        win.setWidth(500);
        win.setShowCloseButton(true);
        win.centerInPage();
        win.addCloseClickHandler(new CloseClickHandler() {
            public void onCloseClick(CloseClientEvent event) {
                win.destroy();
            }
        });

        win.addItem(new FeedbackForm(feedback));
        win.show();
    }
}
